package com.tongfutele.utils;

import com.thoughtworks.xstream.XStream;
import com.tongfutele.op.RespChangePdInfo;
import com.tongfutele.op.query.ClientQueryInfo;
import com.tongfutele.op.query.UsrQueryInfo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class MessageUtil {

    /**
     * xml 转 map
     * @param request
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Map<String,String> xml2map(HttpServletRequest request) throws DocumentException, IOException {
        Map<String,String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);

        Element root = doc.getRootElement();

        List<Element> list = root.elements();

        for (Element element:list) {
            map.put(element.getName(), element.getText());
        }
        ins.close();
        return map;
    }

    /**
     * xml 转 map
     * @param xmlStr xml 字符串
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Map<String,String> xml2map(String xmlStr) throws DocumentException, IOException {
        Map<String,String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        Document doc = reader.read(new ByteArrayInputStream(xmlStr.getBytes("utf-8")));

        Element root = doc.getRootElement();

        List<Element> list = root.elements();

        for (Element element:list) {
            map.put(element.getName(), element.getText());
        }

        return map;
    }

    /**
     * xml 转 map
     * @param xmlStr xml 字符串
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static Map<String,String> xml2map(String xmlStr,int i) throws DocumentException, IOException {
        Map<String,String> map = new HashMap<>();
        SAXReader reader = new SAXReader();

        Document doc = reader.read(new ByteArrayInputStream(xmlStr.getBytes("utf-8")));

        Element root = doc.getRootElement();

        List<Element> list = root.elements();

        for (Element element:list) {
            map.put(element.getName(), element.getText());
        }

        Element AccountInfo = root.element("AccountInfo");
        if (AccountInfo!=null){
            List<Element> AccountInfos = AccountInfo.elements();

            for (Element element: AccountInfos){
                map.put(element.getName(), element.getText());
            }
        }

        return map;
    }

    /**
     * xml转map 不带属性
     * @param xmlStr
     * @param needRootKey 是否需要在返回的map里加根节点键
     * @return
     * @throws DocumentException
     */
    public static Map xml2map(String xmlStr, boolean needRootKey) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        Map<String, Object> map = (Map<String, Object>) xml2map(root);
        if(root.elements().size()==0 && root.attributes().size()==0){
            return map;
        }
        if(needRootKey){
            //在返回的map里加根节点键（如果需要）
            Map<String, Object> rootMap = new HashMap<String, Object>();
            rootMap.put(root.getName(), map);
            return rootMap;
        }
        return map;
    }

    /**
     * xml转map 不带属性
     * @param e
     * @return
     */
    private static Map xml2map(Element e) {
        Map map = new LinkedHashMap();
        List list = e.elements();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Element iter = (Element) list.get(i);
                List mapList = new ArrayList();

                if (iter.elements().size() > 0) {
                    Map m = xml2map(iter);
                    if (map.get(iter.getName()) != null) {
                        Object obj = map.get(iter.getName());
                        if (!(obj instanceof List)) {
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(m);
                        }
                        if (obj instanceof List) {
                            mapList = (List) obj;
                            mapList.add(m);
                        }
                        map.put(iter.getName(), mapList);
                    } else
                        map.put(iter.getName(), m);
                } else {
                    if (map.get(iter.getName()) != null) {
                        Object obj = map.get(iter.getName());
                        if (!(obj instanceof List)) {
                            mapList = new ArrayList();
                            mapList.add(obj);
                            mapList.add(iter.getText());
                        }
                        if (obj instanceof List) {
                            mapList = (List) obj;
                            mapList.add(iter.getText());
                        }
                        map.put(iter.getName(), mapList);
                    } else
                        map.put(iter.getName(), iter.getText());
                }
            }
        } else
            map.put(e.getName(), e.getText());
        return map;
    }
    /**
     * 对象转xml
     * @param object
     * @return
     */
    public static String bean2xml(Object object){
        XStream xStream = new XStream();
        xStream.alias("Package",object.getClass());
        return xStream.toXML(object);
    }


    /**
     * 初始化响应数据包 Xml String
     * @param streamingNo
     * @param OPFlag
     * @param returnStatus
     * @param summary
     * @return
     */
    public static String initRespPdInfoXml(String streamingNo, String OPFlag, String returnStatus, String summary){
        RespChangePdInfo pdInfo = new RespChangePdInfo();
        pdInfo.setOPFlag(OPFlag);
        pdInfo.setReturnStatus(returnStatus);
        pdInfo.setStreamingNo(streamingNo);
        pdInfo.setSummary(summary);

        return bean2xml(pdInfo);
    }


    /**
     * 用户查询请求初始化
     * @param streamingNo
     * @param OPFlag
     * @param SIID
     * @param TimeStamp
     * @param ProductID
     * @param OfferID
     * @param Password
     * @param CustID
     * @param CustAccount
     * @param UserID
     * @param Summary
     * @return
     */
    public static String initUsrQueryInfoXml(String streamingNo, String OPFlag, String SIID, String TimeStamp,
                                             String ProductID, String OfferID, String Password, String CustID,
                                             String CustAccount, String UserID, String Summary){
        UsrQueryInfo info = new UsrQueryInfo();
        info.setTimeStamp(TimeStamp);
        info.setSummary(Summary);
        info.setSIID(SIID);
        info.setProductID(ProductID);
        info.setPassword(Password);
        info.setOPFlag(OPFlag);
        info.setOfferID(OfferID);
        info.setCustID(CustID);
        info.setCustAccount(CustAccount);
        info.setStreamingNo(streamingNo);
        info.setUserID(UserID);

        return bean2xml(info);
    }

    /**
     * 客户查询请求初始化
     * @param streamingNo
     * @param OPFlag
     * @param SIID
     * @param TimeStamp
     * @param ProductID
     * @param OfferID
     * @param Password
     * @param CustID
     * @param CustAccount
     * @param UserID
     * @param Summary
     * @param BizID
     * @param AreaCode
     * @return
     */
    public static String initClientQueryInfoXml(String streamingNo, String OPFlag, String SIID, String TimeStamp,
                                             String ProductID, String OfferID, String Password, String CustID,
                                             String CustAccount, String UserID, String Summary,
                                                String BizID, String AreaCode){
        ClientQueryInfo info = new ClientQueryInfo();
        info.setTimeStamp(TimeStamp);
        info.setSummary(Summary);
        info.setSIID(SIID);
        info.setProductID(ProductID);
        info.setPassword(Password);
        info.setOPFlag(OPFlag);
        info.setOfferID(OfferID);
        info.setCustID(CustID);
        info.setCustAccount(CustAccount);
        info.setStreamingNo(streamingNo);
        info.setUserID(UserID);
//        info.setAccessNo(AccessNo);
        info.setAreaCode(AreaCode);
        info.setBizID(BizID);

        return bean2xml(info);
    }

    /**
     * @param str
     * @return true if str is blank
     */
    public static boolean isBlank(String str){
        return str==null&&str.trim().length()==0;
    }
}
